<template>
  <div class="md-experience-apply-container">
    <div class="md-step-box">
      <el-steps :active="active" simple>
        <el-step title="Personal Information" icon="el-icon-user"></el-step>
        <el-step title="Comfort Zone" icon="el-icon-wind-power"></el-step>
        <el-step title="Works & Influence" icon="el-icon-set-up"></el-step>
      </el-steps>
      <div class="md-step-main">
        <template v-if="active === 0">
          <p class="step-title">Personal Information</p>
          <div class="md-step-block">
            <el-form label-width="180px" :model="form" :rules="rules" ref="formFirstStep">
              <el-form-item prop="name" label="name">
                <el-input v-model="form.firstName" style="width: 200px" placeholder="First Name" />
                <el-input v-model="form.lastName" style="width: 200px" placeholder="Last Name" />
              </el-form-item>
              <el-form-item prop="sex" label="sex">
                <el-radio-group v-model="form.sex">
                  <el-radio label="0">male</el-radio>
                  <el-radio label="1">female</el-radio>
                </el-radio-group>
              </el-form-item>
              <!-- <el-form-item prop="birthday" label="birthday">
                <el-date-picker
                  v-model="form.birthday"
                  type="date"
                  class="w-300"
                  placeholder="please select date">
                </el-date-picker>
              </el-form-item> -->
              <el-form-item prop="email" label="email">
                <el-input v-model="form.email" class="w-300" placeholder="please input" />
              </el-form-item>
              <el-form-item prop="phone" label="contact number">
                <el-input v-model="form.phone" class="w-300" placeholder="please input" />
              </el-form-item>
              <el-form-item prop="zipCode" label="Postal code/ZIP Code">
                <el-input v-model="form.zipCode" class="w-300" placeholder="Postal code/ZIP Code" />
              </el-form-item>
              <el-form-item prop="countryCode" label="Country">
                <VueCountryIntl v-model="form.countryCode" class="w-300" placeholder="please select country" @onChange="countryChange"></VueCountryIntl>
              </el-form-item>
              <el-form-item prop="state" label="State/Province/Region">
                <el-input v-model="form.state" class="w-300" placeholder="State/Province/Region" />
              </el-form-item>
              <el-form-item prop="city" label="City">
                <el-input v-model="form.city" class="w-300" placeholder="City" />
              </el-form-item>
              <el-form-item prop="address" label="Address">
                <el-input type="textarea" v-model="form.address" class="w-300" placeholder="Address" :autosize="{ minRows: 5, maxRows: 5}" />
              </el-form-item>
            </el-form>
          </div>
        </template>
        <template v-if="active === 1">
          <p class="step-title">Comfort Zone <span>(max select 5 items)</span></p>
          <div class="md-step-block">
            <!-- <ul class="tag-list">
              <li class="tag-item"></li>
            </ul> -->
            <el-checkbox-group v-model="scopes" size="mini">
              <el-checkbox class="checkbox-item" :label="item.dictValue" border v-for="item in scopesInfo" :key="item.dictValue">{{ item.dictLabel }}</el-checkbox>
            </el-checkbox-group>
          </div>
        </template>
        <template v-if="active === 2">
          <p class="step-title">Works & Influence</p>
          <div class="md-step-block">
            <p class="step-title" style="font-size: 14px;">Personal Influence</p>
            <div class="step-personal-works">
              <el-form inline :model="personalForm" ref="personalFormRef">
                <div v-for="(person, index) in personalForm.influence" :key="index">
                  <el-form-item prop="name">
                    <p>platform</p>
                    <el-input v-model="person.platform" style="width: 240px" placeholder="Please input" />
                  </el-form-item>
                  <el-form-item prop="phone">
                    <p>platform URL</p>
                    <el-input v-model="person.link" style="width: 240px" placeholder="Please input" />
                  </el-form-item>
                  <el-form-item prop="password">
                    <p>fun count</p>
                    <el-input-number v-model="person.fansNumber" :min="0" :max="9999999999" label="Please input"></el-input-number>
                  </el-form-item>
                  <el-form-item>
                    <p>operate</p>
                    <el-button type="primary" @click.prevent="handleAddPersonalInfluence(person)">add</el-button>
                    <el-button @click.prevent="handleRemovePersonalInfluence(index)" v-if="personalForm.influence.length > 1">remove</el-button>
                  </el-form-item>
                </div>
              </el-form>
            </div>
            <p class="step-title" style="font-size: 14px">Personal work</p>
            <div class="step-personal-works" v-for="(work, index) in personalForm.works" :key="index">
              <el-input style="width: 600px; margin-right: 10px" v-model="work.link" placeholder="Please input works URL" />
              <el-button type="primary" @click.prevent="handleAddPersonalWorks(work)">add</el-button>
              <el-button @click.prevent="handleRemovePersonalWorks(index)" v-if="personalForm.works.length > 1">remove</el-button>
            </div>
            <!-- <p class="step-title" style="font-size: 14px; margin: 20px 0">address</p>
            <el-button type="primary" @click.prevent="choseAddress" v-if="!currentRow">Delivery Address</el-button>
            <el-input v-else v-model="currentRow.address" style="width: 650px">
              <el-button slot="append" icon="el-icon-s-flag" @click.prevent="choseAddress"></el-button>
            </el-input> -->
          </div>
        </template>
      </div>
      <div class="btn-box">
        <el-button type="primary" @click="prevStep" v-if="active > 0">prev</el-button>
        <el-button type="primary" @click="nextStep" v-if="active < 2">next</el-button>
        <el-button type="primary" @click="handleSubmit" v-if="active === 2">submit</el-button>
        <nuxt-link to="/">Leave Blank</nuxt-link>
      </div>
    </div>
  </div>
</template>
<script>
let VueCountryIntl
if (process.client) {
  VueCountryIntl = require('vue-country-intl') // 这里的意思就是写你在 window 对象上的操作，可以翻译为下面这段代码
  require('vue-country-intl/lib/vue-country-intl.css')
}
export default {
  name: 'MdExperiencerApplyComponent',
  layout: 'dynamic',
  components: {
    VueCountryIntl: VueCountryIntl
  },
  data () {
    const validateEMail = (rule, value, callback) => {
      const reg = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/
      if (value === '') {
        callback(new Error('This field is required!'))
      } else if (!reg.test(value)) {
        callback(new Error('Email invalid'))
      } else {
        callback()
      }
    }
    return {
      active: 0,
      form: {
        name: '',
        firstName: '',
        lastName: '',
        sex: '',
        // birthday: '2000-01-01',
        phone: '',
        email: '',
        countryCode: '',
        country: '',
        state: '',
        city: '',
        zipCode: '',
        address: ''
      },
      scopes: [], // 擅长领域
      scopesInfo: [], // 擅长领域字典项
      personalForm: {
        influence: [
          {
            platform: '',
            link: '',
            fansNumber: ''
          }
        ],
        works: [
          { link: '' }
        ]
      },
      rules: {
        name: [{
          required: true, validator: (rule, value, callback) => {
            if (this.form.firstName === '') {
              callback('First name is required!')
            } else if (this.form.lastName === '') {
              callback('Last name is required!')
            }
            callback()
          }, trigger: 'blur'
        }],
        sex: [{ required: true, message: 'This field is required!', trigger: 'change' }],
        // birthday: [{ required: true, message: 'This field is required!', trigger: 'change' }],
        zipCode: [{ required: true, message: 'This field is required!', trigger: 'blur' }],
        email: [{ required: true, validator: validateEMail, trigger: 'blur' }],
        countryCode: [{ required: true, message: 'This field is required!', trigger: 'blur' }],
        state: [{ required: true, message: 'This field is required!', trigger: 'blur' }],
        city: [{ required: true, message: 'This field is required!', trigger: 'blur' }],
        phone: [{ required: true, message: 'This field is required!', trigger: 'blur' }],
        address: [{ required: true, message: 'This field is required!', trigger: 'blur' }]
      }
    }
  },
  mounted () {
    console.log(this.$route)
    this.getItemsInfo()
  },
  methods: {
    async getItemsInfo () {
      const res = await this.$axios.get('web/sysDict/type/md_scopes')
      if (res.code == 200) {
        this.scopesInfo = res.data
      }
    },
    prevStep () {
      if (this.active <= 0) {
        return
      }
      this.active--
    },
    nextStep () {
      if (this.active >= 2) {
        return
      }
      if (this.active === 0) { // 第一步校验
        let flag
        this.$refs.formFirstStep.validate(valid => {
          if (valid) {
            flag = true
          } else {
            flag = false
          }
        })
        if (!flag) {
          return
        }
      }
      if (this.active === 1 && !this.scopes.length) {
        this.$message.error('Please select!')
        return
      }
      this.active++
    },
    countryChange (obj) {
      this.form.country = `${obj.dialCode},${obj.name}`
    },
    handleAddPersonalInfluence (person) {
      const flag = Object.values(person).some(e => e === '')
      if (flag) {
        this.$message.error('Platform fields is required')
        return
      }
      this.personalForm.influence.push({
        platform: '',
        link: '',
        fansNumber: ''
      })
    },
    handleAddPersonalWorks (work) {
      if (!work.link) {
        this.$message.error('work URL is required')
        return
      }
      this.personalForm.works.push({
        link: ''
      })
    },
    handleRemovePersonalInfluence (index) {
      if (this.personalForm.influence.length <= 1) {
        return
      }
      this.personalForm.influence.splice(index, 1)
    },
    handleRemovePersonalWorks (index) {
      if (this.personalForm.works.length <= 1) {
        return
      }
      this.personalForm.works.splice(index, 1)
    },
    async handleSubmit () {
      // 判断 个人影响力是否存在未填写项
      const flag = this.personalForm.influence.some(person => {
        return Object.values(person).some(e => e === '')
      })
      if (flag) {
        this.$message.error('Platform fields is required')
        return
      }
      // 判断 个人作品 是否存在未填写项
      // const flag1 = this.personalForm.works.some(work => {
      //   return work.link === ''
      // })
      // if (flag1) {
      //   this.$message.error('work URL is required')
      //   return
      // }

      const options = {
        ...this.form,
        name: this.form.firstName + '/' + this.form.lastName,
        ...this.personalForm,
        scopes: this.scopes.join(','),
        influence: JSON.stringify(this.personalForm.influence),
        works: JSON.stringify(this.personalForm.works),
        status: '2', // 状态（0正常 1停用 2待审核 3审核成功 4审核失败 5待发货 6待收货 7待收货 8已完成）
        userId: this.$local.getItem('user').userId
      }
      const res = await this.$axios.post('web/userExperiencer', options)
      if (res.code == 200) {
        this.$message.success('apply success!')
        console.log(this.$route.query)

        if (this.$route.query.path) {
          const Qk = Object.keys(this.$route.query)
          let Pa = this.$route.query.path
          if (Qk.length > 0) {
            Pa += '?'
            Pa += Qk.filter(key => key !== 'path').map(key => { return `${key}=${this.$route.query[key]}` }).join('&')
          }
          this.$router.push(Pa)
        } else {
          this.$router.push('/')
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.md-experience-apply-container {
  width: 100%;
  min-height: calc(100vh - 66px);
  background-color: #fff;
  padding: 30px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: center;
  .md-step-box {
    width: 1200px;
  }
  .md-step-main {
    margin: 30px 0;
    width: 1000px;
    .step-title {
      font-size: 16px;
      color: #333;
      position: relative;
      &::before {
        position: absolute;
        top: 0;
        left: -8px;
        content: '';
        height: 16px;
        width: 3px;
        background-color: $md-primary-color;
      }
      span {
        font-size: 14px;
        color: #888;
      }
    }
    .md-step-block {
      width: 100%;
      margin-top: 20px;
      .checkbox-item {
        margin-bottom: 20px;
        margin-left: 0 !important;
      }
      .step-personal-works {
        margin-top: 20px;
      }
    }
  }
  .btn-box {
    display: flex;
    align-items: center;
    justify-content: center;
    a {
      color: $md-primary-color;
      margin-left: 20px;
      font-size: 16px;
    }
  }
}
.w-300 {
  width: 300px;
}
::v-deep .vue-country-intl .country-intl-label {
  box-sizing: border-box;
  padding: 0 10px;
}
::v-deep .vue-country-item {
  padding: 0 10px;
}
</style>
